<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2018 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2018/9/17
 * Time: 上午10:24
 */

namespace App\Library\Cms;

use App\Library\AuthenticatedUser;
use App\Models\PostCatlog;
use App\Models\PostItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

trait PostItemTrait
{
    use AuthenticatedUser;

    protected function storePost(Request $request)
    {
        $aid = $request->input('aid');
        $postitem = $request->post('postitem');
        $content  = $request->post('content');
        $media    = $request->post('media');
        $images   = $request->post('images');
        $validate = Validator::make($postitem, [
            'title' => 'bail|required|string',
        ],[
            'title' => [
                'required' => trans('post.post title required'),
                'string' => trans('post.post title must a string')
            ]
        ]);

        if ($validate->fails()) {
            foreach ($validate->getMessageBag() as $messages)
            {
                foreach ($messages as $message) {
                    return $message;
                }
            }
        }

        if (!$postitem['from'])
        {
            $postitem['from'] = env('APP_NAME');
        }

        if (!$postitem['fromurl'])
        {
            $postitem['fromurl'] = env('APP_URL');
        }

        if (empty($postitem['summary']))
        {
            $postitem['summary'] = mb_substr(stripHtml($content['content']), 120);
        }

        $postitem['summary'] = str_replace('&amp;', '&', $postitem['summary']);
        $postitem['summary'] = str_replace('&nbsp;', '', $postitem['summary']);
        $postitem['summary'] = str_replace('　', '', $postitem['summary']);
        $postitem['summary'] = preg_replace('/\s/', '', $postitem['summary']);

        $postitem['created_at'] = $postitem['created_at'] ? strtotime($postitem['created_at']) : time();

        if ($aid)
        {
            if ($this->authenticateOwner())
            {
                $post = $this->user()->posts()->find($aid);
            } else {
                $post = PostItem::find($aid);
            }

            if ($post) {
                //$postitem['updated_at'] = time();
                $post->update($postitem);
                $post->content()->update($content);

                if ($media)
                {
                    if ($post->media)
                    {
                        $post->media()->update($media);
                    } else {
                        $post->media()->create($media);
                    }
                }


                if ($images)
                {
                    $postImgs = [];
                    $post->images()->get()->map(function ($image) use (&$postImgs, $images){
                        if (!isset($images[$image->id]))
                        {
                            $image->delete();
                        } else {
                            $postImgs[$image->id] = $image;
                        }
                    });

                    $displayorder = 0;
                    foreach ($images as $id=>$img){
                        $img['displayorder'] = $displayorder;
                        if (isset($postImgs[$id])) {
                            $post->images()->where('id', $id)->update($img);
                        } else {
                            $post->images()->create($img);
                        }
                        $displayorder++;
                    }

                    //将第一张设为文章图片
                    if (!$post->image) {
                        $image = reset($images);
                        $post->update(['image'=>$image['image']]);
                    }
                }
            }
        } else {

            $postitem['username'] = $this->user()->username;
            $post = $this->user()->posts()->create($postitem);
            $post->content()->create($content);

            if ($media)
            {
                $post->media()->create($media);
            }

            if ($images)
            {
                foreach ($$images as $image) {
                    $post->images()->create($image);
                }
            }
        }

        return $post;
    }

    public function getItem(Request $request)
    {
        $aid  = $request->input('aid');
        $item = PostItem::available()->find($aid);
        if ($item)
        {
            $item->increment('views');
            return ajaxReturn([
                'item'=>$item,
                'content'=>$item->content,
                'media'=>$item->media,
                'images'=>$item->images
            ]);
        } else {
            return false;
        }
    }

    public function getItemList(Request $request)
    {
        $catid = $request->input('catid');
        $query = PostItem::with('catlog')->available();

        if ($catid) {
            $catIds = PostCatlog::fetchAllChildIds($catid);
            $query = $query->whereIn('catid', $catIds);
        }

        $offset = $request->input('offset') ? $request->input('offset') : 0;
        $count = $request->input('count') ? $request->input('count') : 20;

        $items = $query->offset($offset)->limit($count)->orderByDesc('aid')->get()->map(function ($item){
            $item->image = $item->image ? image_url($item->image) : '';
            $item->formatted_time = date('Y-m-d H:i', $item->created_at);
            return $item;
        });

        return ajaxReturn(['items'=>$items]);
    }

    /**
     * @return bool
     */
    protected function authenticateOwner()
    {
        return true;
    }
}
